
/*
 * Copyright (C) 2010 Bitglue. All rights reserved.
 *
 * $Id: DirectoryScanner.java bself $
 */

package com.bitglue.osgi.scan;

import com.bitglue.osgi.model.Deployment;

import java.io.File;
import java.util.Collection;

import org.apache.commons.io.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StopWatch;

/**
 * BaseScanner implements {@link ScannerInterface} to
 * provide common persistence and parsing scanning
 * functionality to sub class instances.
 * @author Bryan Patrick Self
 */
public class DirectoryScanner extends BaseScanner
  implements InitializingBean {

    private Logger log = LoggerFactory.getLogger(getClass());

    public DirectoryScanner(String[] exts) {
        super(exts);
    }

    @SuppressWarnings("unchecked")
    public void scan() {
        if (!plugable.isReady() || !enabled)
            return;
        log.trace("directory scanner initiating scan on " + scanTarget);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Collection<File> newFiles = FileUtils.listFiles(
         new File(scanTarget), exts, recursive);
        for (File file : newFiles)
             processFile(file);
        mergeDatabase();
        stopWatch.stop();
        log.trace("directory scanner completed scan: "
          + stopWatch.shortSummary());
    }

    protected void processFile(File file) {
        String leaf = file.getName();
        String src = file.toURI().toString();
        Deployment d = parseResource(leaf);
        if (d == null)
            return;
        d.setSource(src);
        Deployment tmp = batch.get(d.getModule());
        if (tmp != null) {
            if (isVersionLessOrEqualTo(d, tmp.getVersion())) {
                log.debug("ignoring dir module " + d.getModule()
                  + " @ " + d.getVersion() + " since "
                  + "duplicate mod version >= " + tmp.getVersion());
                return;
            } else {
                log.debug("ignoring dir module " + tmp.getModule()
                  + " @ " + tmp.getVersion() + " since "
                  + "duplicate mod version > " + d.getVersion());
                FileUtils.deleteQuietly(new File(tmp.getRepoEntry()));
            }
        }
        log.trace("adding deployment resource of " + leaf);
        d.setRepoEntry(repository + "/" + leaf);
        batch.put(d.getModule(), d);
    }

}
